<template>
  <div class="upload-image">
    <el-upload
      :action="action"
      :on-exceed="handleExceed"
      :before-upload="beforeUpload"
      :limit="limit"
      :headers="headers"
      :multiple="multiple"
      :list-type="card ? 'picture-card' : ''"
      v-model:file-list="list"
      :on-success="handleSuccess"
      :show-file-list="showFileList"
      :on-remove="handleRemove"
      :on-preview="handlePreview"
    >
      <slot>
        <el-icon>
          <Plus />
        </el-icon>
      </slot>
      <template #tip v-if="alertShow">
        <div class="el-upload__tip">{{ alert }}</div>
      </template>
    </el-upload>
    <el-dialog v-model="preview.show">
      <img :src="preview.url" />
    </el-dialog>
  </div>
</template>
<script setup>
import Cookies from "js-cookie";
import { Plus } from "@element-plus/icons-vue";
import { watch, toRaw, ref, reactive } from "vue";
import { ElMessage } from "element-plus";
let props = defineProps({
  // 上传数量
  limit: {
    type: Number,
    default: 10,
  },
  // 是否卡片式
  card: {
    type: Boolean,
    default: true,
  },
  // 显示已上传列表
  showFileList: {
    type: Boolean,
    default: true,
  },
  // 多选
  multiple: {
    type: Boolean,
    default: false,
  },
  // 提示
  alert: {
    type: String,
    default: "",
  },
  // 提示显示
  alertShow: {
    type: Boolean,
    default: true,
  },
  // 大小MB
  size: {
    type: Number,
    default: 2,
  },
  // 默认图片
  imageList: {
    type: Array,
    default: [],
  },
});
let headers = { token: Cookies.get("token") };
const emit = defineEmits(["getImageList"]);

let list = ref([]);
list.value = JSON.parse(JSON.stringify(toRaw(props.imageList)));
watch(
  () => props.imageList,
  (val) => {
    if (val instanceof Array) list.value = JSON.parse(JSON.stringify(toRaw(val)));
  }
);

// 上传成功
const handleSuccess = (ref, file, files) => {
  file.url = ref.data.path;
  let arr = [];
  list.value.forEach((item) => {
    if (item.response) arr.push({ url: item.url, name: item.name, size: item.size });
    else arr.push({ url: item.url, name: item.name, size: item.size });
  });
  emit("getImageList", arr);
};

// 删除
const handleRemove = () => {
  let arr = [];
  list.value.forEach((item) => arr.push({ url: item.url, name: item.name, size: item.size }));
  emit("getImageList", arr);
};

// 类型白名单
let whiteType = ["jpg", "jpeg", "png"];
// 上传前
const beforeUpload = (file) => {
  // 类型
  const type = file.name.split(".")[file.name.split(".").length - 1];
  if (!whiteType.includes(type)) {
    ElMessage({ type: "error", message: "图片格式只支持 " + whiteType.join(" ") });
    return false;
  }

  // 大小
  const size = file.size / 1024 / 1024;
  if (size > props.size) {
    ElMessage({ type: "error", message: "图片大小不能超过 " + props.size + " MB" });
    return false;
  }
};

// 提示
let alert = ref("图片只支持 " + whiteType.join(" ") + " , 大小 " + props.size + " MB" + props.alert);

// 超出限制
let handleExceed = () => ElMessage({ type: "error", message: "图片数量不能超过 " + props.limit + " 个" });
// 预览
let preview = reactive({ show: false, url: "" });
let handlePreview = (image) => {
  preview.show = true;
  preview.url = image.url;
};

// 上传路径
// let action = process.env.NODE_ENV == "development" ? "/api/common/upload" : "/admin/api/common/upload";
let action =  import.meta.env.VITE_REQUEST + '/api/common/upload';
</script>
<style scoped lang="scss">
.upload-image {
  .el-alert {
    margin-top: 10px;
    line-height: initial;
  }

  :deep(.el-dialog) {
    width: fit-content;

    .el-dialog__header {
      padding-bottom: 0;
      padding-top: 0;

      .el-dialog__headerbtn .el-dialog__close {
        font-size: 25px;
        padding: 3px;
        background-color: rgba(255, 255, 255, 0.5);
        border-radius: 3px;
        color: #333;
      }
    }

    .el-dialog__body {
      padding: 0;

      img {
        max-width: 100%;
        display: block;
      }
    }
  }
}
</style>
